<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>

const data = [
  {id:"01", name: "张大大", pid:"", job: "项目经理"},
  {id:"02", name: "小亮", pid:"01", job: "产品leader"},
  {id:"03", name: "小美", pid:"01", job: "UIleader"},
  {id:"04", name: "老马", pid:"01", job: "技术leader"},
  {id:"05", name: "老王", pid:"01", job: "测试leader"},
  {id:"06", name: "老李", pid:"01", job: "运维leader"},
  {id:"07", name: "小丽", pid:"02", job: "产品经理"},
  {id:"08", name: "大光", pid:"02", job: "产品经理"},
  {id:"09", name: "小高", pid:"03", job: "UI设计师"},
  {id:"10", name: "小刘", pid:"04", job: "前端工程师"},
  {id:"11", name: "小华", pid:"04", job: "后端工程师"},
  {id:"12", name: "小李", pid:"04", job: "后端工程师"},
  {id:"13", name: "小赵", pid:"05", job: "测试工程师"},
  {id:"14", name: "小强", pid:"05", job: "测试工程师"},
  {id:"15", name: "小涛", pid:"06", job: "运维工程师"},
  {id:"16", name: "小X", pid:"08", job: "xxxx"}
]

// 完成代码
function arrToTree(list) {
  // 定义一个需要存放的树行结构的数据
  const treeData = []
  // 对传入的数据进行遍历
   list.forEach (item => {
    // 查看是否的pid值,如果没有就是顶级,直接添到treeData中
    if(!item.pid) {
      treeData.push(item)
    }
    // 查看子级 子级需要和list中每一项进行对比
    // 对比关系 : 每一项的pid是否等于当前项的id
    const children = list.filter(data => data.pid === item.id)
    // 查看children是否存在子级,如果没有,不能做任何处理
    if(!children.length) return
    // 如果children 有数据, 就应该吧数据赋值当父级
    item.children = children

   })
   return treeData

  
  }
  const treeData = arrToTree(data)
  console.log(treeData);

  </script>
</body>
</html>